package com.ohuang.imghide

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Log
import android.widget.SeekBar
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.ohuang.imghide.databinding.ActivityMainBinding
import com.ohuang.imghide.hidetank.BlackHideTank
import com.ohuang.imghide.hidetank.ColourHideTank
import com.ohuang.imghide.share.FileUtil
import com.ohuang.imghide.share.Share2
import com.ohuang.imghide.share.ShareContentType
import com.ohuang.imghide.util.BitmapUtil
import com.ohuang.imghide.util.FileUtils
import com.ohuang.imghide.util.PhotoUtil
import java.io.File

class MainActivity : ViewBindActivity<ActivityMainBinding>() {
    val TAG = MainActivity::class.java.simpleName

    private var bitmap0: Bitmap? = null
    private var bitmap1: Bitmap? = null
    private var bitmap: Bitmap? = null
    private var select: Int = 0
    private var bgBlack = false
    private var isRun = false

    override fun getViewBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun initView() {
        initEvent()
        requestPower()
    }

    private fun initEvent() {
        binding?.image0?.setOnClickListener {
            if (isRun) {
                Toast.makeText(this, "正在运行中", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            select = 0
            PhotoUtil.getPhotoLib(this)
        }
        binding?.image1?.setOnClickListener {
            if (isRun) {
                Toast.makeText(this, "正在运行中", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            select = 1
            PhotoUtil.getPhotoLib(this)
        }

        binding?.imageResult?.setOnClickListener {
            if (isRun) {
                Toast.makeText(this, "正在运行中", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            if (bitmap != null) {
                Thread {
                    isRun = true
                    saveToShare()
                    isRun = false
                }.start()

            } else {
                Toast.makeText(this, "请生成图片后再保存", Toast.LENGTH_LONG).show()
            }
        }


        binding?.btnGenerate?.setOnClickListener {
            if (checkCanGenerate()) return@setOnClickListener
            Thread {
                isRun = true
                val create = BlackHideTank.create(bitmap0, bitmap1)
                bitmap = create
                runOnUiThread {
                    if (bitmap != null) {
                        binding?.imageResult?.setImageBitmap(bitmap)
                    } else {
                        Toast.makeText(this, "生成失败", Toast.LENGTH_LONG).show()
                    }
                }
                isRun = false
            }.start()


        }
        binding?.btnGenerateColour?.setOnClickListener {
            if (checkCanGenerate()) return@setOnClickListener

            Thread {
                isRun = true
                val create = ColourHideTank.create(bitmap0, bitmap1)
                bitmap = create
                runOnUiThread {
                    if (bitmap != null) {
                        binding?.imageResult?.setImageBitmap(bitmap)
                    } else {
                        Toast.makeText(this, "生成失败", Toast.LENGTH_LONG).show()
                    }
                }
                isRun = false
            }.start()
        }

        binding?.btnChangeBg?.setOnClickListener {
            bgBlack = if (bgBlack) {
                binding?.layout?.setBackgroundColor(-1)
                false
            } else {
                binding?.layout?.setBackgroundColor(0xff000000.toInt())
                true
            }
        }
        binding?.btnSaveImage?.setOnClickListener {
            if (isRun) {
                Toast.makeText(this, "正在运行中", Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }
            if (bitmap != null) {
                Thread {
                    isRun = true
                    saveImage()
                    isRun = false
                }.start()

            } else {
                Toast.makeText(this, "请生成图片后再保存", Toast.LENGTH_LONG).show()
            }

        }

        binding?.sbR?.setOnSeekBarChangeListener(object :SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                binding?.tvWeightR?.text="红：$p1"
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {

            }

            override fun onStopTrackingTouch(p0: SeekBar?) {

            }

        })
        binding?.sbG?.setOnSeekBarChangeListener(object :SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                binding?.tvWeightG?.text="绿：$p1"
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {

            }

            override fun onStopTrackingTouch(p0: SeekBar?) {

            }

        })
        binding?.sbB?.setOnSeekBarChangeListener(object :SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                binding?.tvWeightB?.text="蓝：$p1"
            }

            override fun onStartTrackingTouch(p0: SeekBar?) {

            }

            override fun onStopTrackingTouch(p0: SeekBar?) {

            }

        })

        binding?.btnGenerateCustom?.setOnClickListener {
            if (checkCanGenerate()) return@setOnClickListener
            val r=binding?.sbR?.progress
            val g=binding?.sbG?.progress
            val b=binding?.sbB?.progress
            var sum=(r!! + g!! + b!!)

                Thread {
                    isRun = true
                    var create:Bitmap?=null
                    create = if (sum==0) {
                        ColourHideTank.create(bitmap0, bitmap1, 0.333f, 0.333f, 0.333f)
                    }else{
                        ColourHideTank.create(bitmap0, bitmap1, r.toFloat().div(sum), g.toFloat().div(sum), b.toFloat().div(sum))
                    }
                    bitmap = create
                    runOnUiThread {
                        if (bitmap != null) {
                            binding?.imageResult?.setImageBitmap(bitmap)
                        } else {
                            Toast.makeText(this, "生成失败", Toast.LENGTH_LONG).show()
                        }
                    }
                    isRun = false
                }.start()


        }
    }

    private fun checkCanGenerate(): Boolean {
        if (isRun) {
            Toast.makeText(this, "正在运行中", Toast.LENGTH_LONG).show()
            return true
        }
        if (bitmap0 == null) {
            Toast.makeText(this, "请添加图片1", Toast.LENGTH_LONG).show()
            return true
        }
        if (bitmap1 == null) {
            Toast.makeText(this, "请添加图片2", Toast.LENGTH_LONG).show()
            return true
        }
        return false
    }

    private fun saveToShare() {
        val path =
            FileUtils.getRootFile(this).path + File.separator + "Pictures" + File.separator + "imageHide" + File.separator
        val file = File(path)
        if (!file.exists()) {
            file.mkdirs()
        }
        val imgPath = "${path}share.png"
        BitmapUtil.saveBitmapFile(bitmap, imgPath)
        val uri: Uri = FileUtil.getFileUri(this, ShareContentType.FILE, File(imgPath))
        Share2.Builder(this).setContentType(ShareContentType.FILE).setShareFileUri(uri)
            .build().shareBySystem()
    }

    private fun saveImage() {
        val path =
            FileUtils.getRootFile(this).path + File.separator + "Pictures" + File.separator + "imageHide" + File.separator
        val file = File(path)
        if (!file.exists()) {
            file.mkdirs()
        }
        val currentTimeMillis = System.currentTimeMillis()
        val imgPath = "$path$currentTimeMillis.png"
        BitmapUtil.saveBitmapFile(bitmap, imgPath)
        sendBroadcast(
            Intent(
                Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.parse("file://$imgPath")
            )
        )
        runOnUiThread {
            Toast.makeText(this, "已保存$imgPath", Toast.LENGTH_LONG).show()
        }

    }

    private fun requestPower() {
//判断是否已经赋予权限
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
            != PackageManager.PERMISSION_GRANTED
        ) {
            //如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true。
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
            ) {//这里可以写个对话框之类的项向用户解释为什么要申请权限，并在对话框的确认键后续再次申请权限.它在用户选择"不再询问"的情况下返回false
                //申请权限，字符串数组内是一个或多个要申请的权限，1是申请权限结果的返回参数，在onRequestPermissionsResult可以得知申请结果
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1
                )
            } else {
                //申请权限，字符串数组内是一个或多个要申请的权限，1是申请权限结果的返回参数，在onRequestPermissionsResult可以得知申请结果
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 1
                )
            }
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val onActivityResult = PhotoUtil.onActivityResult(requestCode, resultCode, data, this)
        if (onActivityResult != null) {
            readImage(onActivityResult)
        }
    }

    private fun readImage(onActivityResult: File?) {
        var inputStream = onActivityResult?.inputStream()
        val decodeStream = BitmapFactory.decodeStream(inputStream)
        if (select == 0) {
            bitmap0 = decodeStream
            binding?.image0?.setImageBitmap(bitmap0)
        } else if (select == 1) {
            bitmap1 = decodeStream
            binding?.image1?.setImageBitmap(bitmap1)
        }
    }
}